package com.spring.sperapc.web.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONException;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.spera.aliyunContent.AliyunContent;
import com.spera.aliyunUtil.SperaOSSUtil;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.filestream.config.Configurations;
import com.spring.security.filestream.util.TokenUtil;
import com.spring.security.web.dao.JedisCache;
import com.spring.sperapc.web.service.TestService;

/**
 * Created by wojunyu on 2015/7/24.
 */
@Controller
@RequestMapping(value = "/test")
public class TestController {
    static Logger logger = Logger.getLogger(TestController.class.getName());
    @Resource
    private TestService testService;

    @RequestMapping(value = "/queryTest")
    @ResponseBody
    public Object queryTestList(String pageIndex,String pageSize){
        System.out.println("ok---->"+pageIndex+","+pageSize);
        Map<String, Object> datas = new HashMap<String, Object>();
        try{

            PageHelper.startPage(Integer.parseInt(pageIndex) + 1, Integer.parseInt(pageSize));
            List list = testService.queryTestList(null);
            PageInfo page = new PageInfo(list);
            datas.put("total", page.getTotal());
            datas.put("data", list);
            logger.info(datas);
            System.out.println("end "+page.getTotal()+","+list.size());
        }catch(Exception e){
            e.printStackTrace();
        }

        return datas;
    }
    
    
  //----------------------阿里云OSS  MTS方式的断点续传
    @Resource
	private JedisCache jedisCache;
	
  	private static final int CONCURRENCIES = 1; //
  	// 断点上传获取token
  	@RequestMapping(value = "/uploadtk", method = RequestMethod.GET)
  	@ResponseBody
  	public Object uploadtk(HttpServletRequest req, HttpServletResponse resp,
  			String file_name, String file_size) throws ServletException,
  			IOException {
  		final String token = TokenUtil.generateToken(file_name, file_size);
  		Map<String, Object> jsonStr = new HashMap<String, Object>();
  		jsonStr.put("token", token);
//  		int hasin = iosQuestService.checkFileToken(jsonStr);
//  		if (hasin != 0) {
//  			jsonStr.put(ApplicationUtils.STATUS, "2");
//  			jsonStr.put(ApplicationUtils.MSG, "附件已存在");
//  			return jsonStr;
//  		}
  		
  		if (!ApplicationUtils.isNotNull(file_name)) {
  			jsonStr.put(ApplicationUtils.STATUS, "2");
  			jsonStr.put(ApplicationUtils.MSG, "附件名不能为空");
  			return jsonStr;
  		}
  		
  		if (!ApplicationUtils.isNotNull(file_size)) {
  			jsonStr.put(ApplicationUtils.STATUS, "2");
  			jsonStr.put(ApplicationUtils.MSG, "未知附件大小");
  			return jsonStr;
  		}
  		
  	    int partCount = SperaOSSUtil.calPartCount(Long.parseLong(file_size));
          if (partCount < 1) {
          	jsonStr.put(ApplicationUtils.STATUS, "2");
  			jsonStr.put(ApplicationUtils.MSG, "要上传文件的大小必须大于一个Part的字节数：" + AliyunContent.PART_SIZE);
  			return jsonStr;
          }
  		

  		try {
  			//第一次上传附件时，将获取到的token存入缓存(后续断点获取不需要写入缓存,只需调用uploadOssPos去获取)
  			if (!jedisCache.exists(token)) {
//  				ExecutorService pool = Executors.newFixedThreadPool(CONCURRENCIES);
//  				SetToken2RedisThread s = new SetToken2RedisThread(redisCache,token,file_size,partCount+"");
//  				pool.execute(s);
//  				pool.shutdown();
//  		        while (!pool.isTerminated()) {
//  		            try {
//  						pool.awaitTermination(5, TimeUnit.SECONDS);
//  					} catch (InterruptedException e) {
//  						// 
//  						e.printStackTrace();
//  					}
//  		        }
  				
  				ClientConfiguration config = new ClientConfiguration();
  				OSSClient client = new OSSClient(AliyunContent.ossEndPoint,AliyunContent.accessKeyId, AliyunContent.accessKeySecret,config);
//  				//新建oss分片上传任务
  		    	String uploadId = SperaOSSUtil.initMultipartUpload(client, AliyunContent.inputBucket, token);
  				jedisCache.rpush(token, file_size);//文件大小
  				jedisCache.rpush(token, uploadId);//上传请求id  同一个附件必须是同一个上传请求，在未完成分片上传前，请求应该会一直存在
  				jedisCache.rpush(token, "0");//起始位置
  				jedisCache.rpush(token, "1");//起始partId
  				jedisCache.rpush(token, partCount+"");//附件上传任务总共分为多少片
//  				new Thread(){
//  					@Override
//  				    public void run()
//  				    {
//  						
//  				    }
//  				};
  				
  			}
  			
  			if (Configurations.isCrossed())
  				jsonStr.put("server", Configurations.getCrossServer());
  			jsonStr.put(ApplicationUtils.STATUS, "1");
  			jsonStr.put(ApplicationUtils.MSG, "成功");
  		} catch (JSONException e) {
  			jsonStr.put(ApplicationUtils.STATUS, "0");
  			jsonStr.put(ApplicationUtils.MSG, "失败");
  		}
  		System.out.println("TokenServlet---->doGet--->json:" + jsonStr);
  		return jsonStr;
  	}

}
